//
//  GNRefreshControl.swift
//  SinaWeChat
//
//  Created by mac on 15/12/11.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit

// 当前控件的高度
private let RefreshControlH: CGFloat = 50

/// - Normal:     默认状态或者松开手就回到默认状态
/// - Pulling:    (将要刷新)松开手就进入刷新的这么一个状态
/// - Refreshing: 正在刷新
//枚举定义三个状态
enum GNRefreshControlState: Int {
    case Normal = 0
    case Pulling = 1
    case Refreshing = 2
}
class GNRefreshControl: UIControl {
    
    //之前的状态,用于设置成 normal 的时候,判断上一次是否刷新状态
    var oldGnState: GNRefreshControlState = .Normal
    
    //在KVO判定三种状态,在此处写三种状态的执行逻辑
    var gnState:GNRefreshControlState = .Normal{
        
        
        didSet{
            
            switch gnState{
                
            case .Pulling:
                //print("显示'松开刷新'")
                messageLabel.text = "放开起飞"
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    //箭头旋转
                    self.arrowIcon.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))                    })
            case .Refreshing :
                //print("隐藏箭头,菊花转")
                messageLabel.text = "正在起飞"
                arrowIcon.hidden = true
                indicator.startAnimating()
                
                //增加顶部的滑动距离
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    
                    var contentInset = self.scrollView!.contentInset
                    contentInset.top += RefreshControlH
                    self.scrollView?.contentInset = contentInset
                    
                })
                
                //给父控件tableview中的自己发送events
                sendActionsForControlEvents(.ValueChanged)
                
            case .Normal :
                //print("显示箭头,隐藏菊花,变换文字")
                messageLabel.text = "下拉起飞"
                arrowIcon.hidden = false
                indicator.stopAnimating()
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    
                    self.arrowIcon.transform = CGAffineTransformIdentity
                })
                
                //从刷新状态切换到默认状态才会执行下面的代码
                if oldGnState == .Refreshing {
                    //增加顶部的滑动距离
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        
                        var contentInset = self.scrollView!.contentInset
                        contentInset.top -= RefreshControlH
                        
                        self.scrollView?.contentInset = contentInset
                    })
                }
                
            }
            
            oldGnState = gnState
        }
        
    }
    
    //齐备添加道德父控件(可以滚动)
    
    var scrollView:UIScrollView?
    
   override init(frame: CGRect) {
    super.init(frame: frame)
    setupUI()
        
    }
    

   required init?(coder aDecoder: NSCoder) {
       fatalError("init(coder:) has not been implemented")
   }
    
    //MARK : - 结束刷新
    func endRefreshing(){
        
        gnState = .Normal
    }
    
    private func setupUI(){
        
        
        backgroundColor = UIColor.redColor()
        // 暂时先写到
        var frame = self.frame
        frame.size = CGSizeMake(SCREENW, RefreshControlH)
        frame.origin.y = -RefreshControlH
        self.frame = frame
        
        
        // 添加控件
        addSubview(arrowIcon)
        addSubview(messageLabel)
        addSubview(indicator)
        
        //添加约束
        arrowIcon.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(self)
            make.centerX.equalTo(self).offset(-35)
        }
        messageLabel.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(arrowIcon)
            make.leading.equalTo(arrowIcon.snp_trailing).offset(5)
        }
        indicator.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowIcon)
        }
        
        
    }
    
    
    /// 当前控件将要加到某一个控件上的时候会调用此方法,在此处用kvo监听子控件在父控件中的拖动距离来判断不同的状态
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        
        print(newSuperview)
        //判断到底能不能滚动
        if let scrollView  = newSuperview as? UIScrollView {
            
            //利用 KVO
            scrollView.addObserver(self, forKeyPath: "contentOffset", options: [NSKeyValueObservingOptions.New], context: nil)
            self.scrollView = scrollView
            
            
            //可能屏幕的宽度不相同
            var frame = self.frame
            frame.size.width = scrollView.frame.width
            self.frame = frame
            
        }
        
    }
    
    //kVO的监听方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        let contentOffsetY = scrollView?.contentOffset.y
        
        let contentInsetTop = scrollView?.contentInset.top ?? 0
        
        //临界值??
        let conditionValue = -contentInsetTop-RefreshControlH
        
        if scrollView!.dragging {
            
            if gnState == .Normal && contentOffsetY < conditionValue{
                
                gnState = .Pulling
            }else if gnState == .Pulling && contentOffsetY >= conditionValue {
                
                //记住此处的大于 是由于是负数,绝对值是小于的
                    gnState == .Normal
                
            }
            
        }else{
            
            //没在拖动状态,并且已经进入pulling,也就是偏移量大于contionvalue
            if gnState == .Pulling {
                gnState = .Refreshing
            }
        
        }
        
    }
    
    deinit {
        scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    //MARK : -懒加载控件
    private lazy var arrowIcon: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    
    //显示文字的label
    private lazy var messageLabel : UILabel = {
       
        let label = UILabel(textColor: UIColor.grayColor(), fontSize: 12)
        
        label.text = "下拉刷新"
        return label
        
    }()
    
    //菊花转
    private lazy var indicator : UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle:UIActivityIndicatorViewStyle.Gray)

}
